import { createFileRoute } from '@tanstack/react-router'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { 
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { 
  Search,
  Plus,
  Edit,
  Trash2,
  MapPin,
  Settings,
  ChevronDown,
  ChevronRight,
  X
} from 'lucide-react'
import { useState, useEffect, useCallback, useMemo } from 'react'

export const Route = createFileRoute('/seals/regions')({
  component: RegionSealsPage,
})

// 地区数据类型定义
interface Region {
  id: number
  name: string
  code: number
  level: number
  children: Region[]
}

// 印章配置类型定义


// 印章材质类型定义
interface SealMaterial {
  id: number
  typeId: number
  name: string
  status: number  // 0启用 1禁用
  createdAt: number
  updatedAt: number
}

// 印章大类定义
interface SealCategory {
  id: number
  name: string
  description?: string
  needsRegionBinding: boolean  // 是否需要省市绑定
  isActive: boolean
  subTypes: SealSubType[]
}

// 印章子类型定义
interface SealSubType {
  id: number
  categoryId: number
  name: string
  isActive: boolean
}

// 全局价格配置（不需要省市绑定的）
interface SealPrice {
  id: number
  materialId: number
  subTypeId: number
  price: number
  discountPrice: number
}

// 地区价格配置（需要省市绑定的）
interface RegionPrice {
  id: number
  provinceId: number
  provinceName: string
  cityId: number
  cityName: string
  materialId: number
  subTypeId: number
  price: number
  discountPrice: number
}

// API调用函数
const fetchRegions = async (): Promise<Region[]> => {
  try {
    const response = await fetch('/huibanhao/regions', {
      headers: {
        'Accept': 'application/json'
      }
    })
    const result = await response.json()
    if (result.code === 200) {
      return result.data
    }
    throw new Error('获取地区数据失败')
  } catch (error) {
    console.error('获取地区数据失败:', error)
    return []
  }
}

function RegionSealsPage() {
  const [regions, setRegions] = useState<Region[]>([])
  const [loading, setLoading] = useState(true)
  const [searchTerm, setSearchTerm] = useState('')
  const [expandedRegions, setExpandedRegions] = useState<Set<number>>(new Set())

  
  // 弹窗状态
  const [showMaterialModal, setShowMaterialModal] = useState(false)
  const [showSubTypeModal, setShowSubTypeModal] = useState(false)
  const [showRegionModal, setShowRegionModal] = useState(false)
  const [showPriceModal, setShowPriceModal] = useState(false)
  const [selectedCategory, setSelectedCategory] = useState<SealCategory | null>(null)
  
  // 印章材质和分类数据
  const [materials, setMaterials] = useState<SealMaterial[]>([])
  const [currentSubTypes, setCurrentSubTypes] = useState<SealSubType[]>([])
  
  // 固定的4个印章分类
  const [sealCategories] = useState<SealCategory[]>([
    {
      id: 1,
      name: '公司印章',
      description: '企业法人印章，包括公章、财务章、法人章等',
      needsRegionBinding: true,
      isActive: true,
      subTypes: []
    },
    {
      id: 2,
      name: '个体户印章',
      description: '个体工商户经营印章',
      needsRegionBinding: true,
      isActive: true,
      subTypes: []
    },
    {
      id: 3,
      name: '政府宗教团体印章',
      description: '政府机关、事业单位、宗教团体等印章',
      needsRegionBinding: false,
      isActive: true,
      subTypes: []
    },
    {
      id: 5,
      name: '个人印章',
      description: '个人姓名印章、私章等',
      needsRegionBinding: false,
      isActive: true,
      subTypes: []
    }
  ])
  
  useEffect(() => {
    // 不再需要加载印章分类，使用固定数据
  }, [])
  const [globalPrices, setGlobalPrices] = useState<SealPrice[]>([])
  const [regionPrices, setRegionPrices] = useState<RegionPrice[]>([])
  const [selectedCities, setSelectedCities] = useState<{provinceId: number, provinceName: string, cityId: number, cityName: string}[]>([])

  // 优化的价格更新回调函数 - 使用更高效的状态更新策略
  const updateRegionPrice = useCallback((materialId: number, subTypeId: number, field: 'price' | 'discountPrice', value: number) => {
    setRegionPrices(prevPrices => {
      // 创建新的价格数组，避免直接修改原数组
      const newPrices = [...prevPrices]
      const citiesToUpdate = selectedCities || []
      
      // 为每个选中的城市更新或创建价格记录
      citiesToUpdate.forEach(city => {
        const existingIndex = newPrices.findIndex(p => 
          p.materialId === materialId && 
          p.subTypeId === subTypeId && 
          p.cityId === city.cityId
        )
        
        if (existingIndex >= 0) {
          // 更新现有记录 - 只更新需要改变的字段
          newPrices[existingIndex] = {
            ...newPrices[existingIndex],
            [field]: value
          }
        } else {
          // 创建新记录
          newPrices.push({
            id: Date.now() + Math.random() + city.cityId,
            provinceId: city.provinceId,
            provinceName: city.provinceName,
            cityId: city.cityId,
            cityName: city.cityName,
            materialId,
            subTypeId,
            price: field === 'price' ? value : 0,
            discountPrice: field === 'discountPrice' ? value : 0
          })
        }
      })
      
      return newPrices
    })
  }, [selectedCities])

  const updateGlobalPrice = useCallback((materialId: number, subTypeId: number, field: 'price' | 'discountPrice', value: number) => {
    setGlobalPrices(prices => {
      const existingPrice = prices.find(p => 
        p.materialId === materialId && 
        p.subTypeId === subTypeId
      )
      
      if (existingPrice) {
        return prices.map(p => 
          p.id === existingPrice.id ? { ...p, [field]: value } : p
        )
      } else {
        const newPrice: SealPrice = {
          id: Date.now() + Math.random(),
          materialId,
          subTypeId,
          price: field === 'price' ? value : 0,
          discountPrice: field === 'discountPrice' ? value : 0
        }
        return [...prices, newPrice]
      }
    })
  }, [])

  // 优化的价格查找函数 - 修复区域价格查找逻辑
  const findRegionPrice = useMemo(() => {
    const priceMap = new Map<string, RegionPrice>()
    regionPrices.forEach(price => {
      // 对于区域价格，需要包含城市ID来区分不同城市的价格
      const key = `${price.materialId}-${price.subTypeId}-${price.cityId}`
      priceMap.set(key, price)
    })
    return (materialId: number, subTypeId: number, cityId?: number) => {
      if (cityId) {
        return priceMap.get(`${materialId}-${subTypeId}-${cityId}`)
      }
      // 如果没有指定城市ID，返回第一个匹配的价格（用于显示）
      for (const [key, price] of priceMap) {
        if (key.startsWith(`${materialId}-${subTypeId}-`)) {
          return price
        }
      }
      return undefined
    }
  }, [regionPrices])

  const findGlobalPrice = useMemo(() => {
    const priceMap = new Map<string, SealPrice>()
    globalPrices.forEach(price => {
      const key = `${price.materialId}-${price.subTypeId}`
      priceMap.set(key, price)
    })
    return (materialId: number, subTypeId: number) => 
      priceMap.get(`${materialId}-${subTypeId}`)
  }, [globalPrices])

  // 防抖函数 - 优化防抖延迟时间
  const debounce = useCallback((func: Function, delay: number) => {
    let timeoutId: NodeJS.Timeout
    return (...args: any[]) => {
      clearTimeout(timeoutId)
      timeoutId = setTimeout(() => func.apply(null, args), delay)
    }
  }, [])

  // 防抖的价格更新函数 - 减少防抖延迟以提升响应性
  const debouncedUpdateRegionPrice = useMemo(
    () => debounce(updateRegionPrice, 200),
    [debounce, updateRegionPrice]
  )

  const debouncedUpdateGlobalPrice = useMemo(
    () => debounce(updateGlobalPrice, 200),
    [debounce, updateGlobalPrice]
  )

  // 加载地区数据
  useEffect(() => {
    const loadRegions = async () => {
      setLoading(true)
      const data = await fetchRegions()
      setRegions(data)
      setLoading(false)
    }
    loadRegions()
  }, [])

  // 切换地区展开状态
  const toggleRegionExpanded = (regionId: number) => {
    const newExpanded = new Set(expandedRegions)
    if (newExpanded.has(regionId)) {
      newExpanded.delete(regionId)
    } else {
      newExpanded.add(regionId)
    }
    setExpandedRegions(newExpanded)
  }

  // 选择印章大类
  const handleSelectCategory = (category: SealCategory) => {
    setSelectedCategory(category)
    // 加载该类别的印章材质
    loadCategoryMaterials(category.id)
    setShowMaterialModal(true)
  }

  // 加载印章材质
  const loadCategoryMaterials = async (typeId: number) => {
    try {
      // 获取JWT token
      const token = localStorage.getItem('auth_token')
      const headers: Record<string, string> = {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      }
      
      // 如果有token，添加Authorization头
      if (token) {
        headers['Authorization'] = token
      }

      const response = await fetch(`/huibanhao/seal/getMaterial?typeId=${typeId}`, {
        method: 'GET',
        headers
      })
      
      const result = await response.json()
      
      if (result.code === 200) {
        if (result.data && Array.isArray(result.data)) {
          setMaterials(result.data)
        } else {
          // 如果没有数据，设置为空数组
          setMaterials([])
        }
      } else {
        console.error('获取印章材质失败:', result.msg)
        setMaterials([])
      }
    } catch (error) {
      console.error('获取印章材质失败:', error)
      setMaterials([])
    }
  }

  // 保存印章材质
  const saveMaterials = async (typeId: number, materialsToSave: SealMaterial[]) => {
    try {
      const materialsData = materialsToSave.map(material => ({
        name: material.name,
        status: material.status
      }))

      // 获取JWT token
      const token = localStorage.getItem('auth_token')
      const headers: Record<string, string> = {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      }
      
      // 如果有token，添加Authorization头
      if (token) {
        headers['Authorization'] = token
      }

      const response = await fetch('/huibanhao/seal/saveMaterial', {
        method: 'POST',
        headers,
        body: JSON.stringify({
          typeId,
          materials: materialsData
        })
      })
      
      const result = await response.json()
      
      if (result.code === 200) {
        // 重新加载材质数据
        await loadCategoryMaterials(typeId)
        return true
      } else {
        console.error('保存印章材质失败:', result.msg)
        return false
      }
    } catch (error) {
      console.error('保存印章材质失败:', error)
      return false
    }
  }

  // 获取印章类型
  const loadCategoryClassify = async (typeId: number) => {
    try {
      // 获取JWT token
      const token = localStorage.getItem('auth_token')
      const headers: Record<string, string> = {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      }
      
      // 如果有token，添加Authorization头
      if (token) {
        headers['Authorization'] = token
      }

      const response = await fetch(`/huibanhao/seal/getClassify?typeId=${typeId}`, {
        method: 'GET',
        headers
      })
      
      const result = await response.json()
      
      if (result.code === 200) {
        if (result.data && Array.isArray(result.data)) {
          // 将获取到的印章类型转换为当前的子类型格式
          const classifyList = result.data.map((item: any) => ({
            id: item.id || Date.now() + Math.random(),
            categoryId: typeId,
            name: item.name,
            isActive: item.status === 0 // 0启用 1禁用
          }))
          setCurrentSubTypes(classifyList)
        } else {
          setCurrentSubTypes([])
        }
      } else {
        console.error('获取印章类型失败:', result.msg)
        setCurrentSubTypes([])
      }
    } catch (error) {
      console.error('获取印章类型失败:', error)
      setCurrentSubTypes([])
    }
  }

  // 保存印章类型
  const saveClassify = async (typeId: number, classifyList: SealSubType[]) => {
    try {
      const classifyData = classifyList.map(item => ({
        name: item.name,
        status: item.isActive ? 0 : 1 // 0启用 1禁用
      }))

      // 获取JWT token
      const token = localStorage.getItem('auth_token')
      const headers: Record<string, string> = {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      }
      
      // 如果有token，添加Authorization头
      if (token) {
        headers['Authorization'] = token
      }

      const response = await fetch('/huibanhao/seal/saveClassify', {
        method: 'POST',
        headers,
        body: JSON.stringify({
          typeId,
          classifyList: classifyData
        })
      })
      
      const result = await response.json()
      
      if (result.code === 200) {
        // 重新加载印章类型数据
        await loadCategoryClassify(typeId)
        return true
      } else {
        console.error('保存印章类型失败:', result.msg)
        return false
      }
    } catch (error) {
      console.error('保存印章类型失败:', error)
      return false
    }
  }

  // 添加印章材质
  const handleAddMaterial = () => {
    if (!selectedCategory) return
    
    const newMaterial: SealMaterial = {
      id: Date.now(),
      typeId: selectedCategory.id,
      name: '',
      status: 0, // 0启用
      createdAt: Date.now(),
      updatedAt: Date.now()
    }
    setMaterials([...(materials || []), newMaterial])
  }

  // 更新印章材质
  const handleUpdateMaterial = (id: number, updates: Partial<SealMaterial>) => {
    setMaterials((materials || []).map(m => m.id === id ? { ...m, ...updates } : m))
  }

  // 删除印章材质
  const handleDeleteMaterial = (id: number) => {
    setMaterials((materials || []).filter(m => m.id !== id))
  }

  // 进入子类型配置
  const handleConfigSubTypes = async () => {
    if (!selectedCategory) return
    
    setShowMaterialModal(false)
    // 获取印章类型数据
    await loadCategoryClassify(selectedCategory.id)
    setShowSubTypeModal(true)
  }

  // 更新印章子类型
  const handleUpdateSubType = (subTypeId: number, updates: Partial<SealSubType>) => {
    setCurrentSubTypes(subTypes => 
      (subTypes || []).map(sub => sub.id === subTypeId ? { ...sub, ...updates } : sub)
    )
  }

  // 添加印章子类型
  const handleAddSubType = () => {
    if (!selectedCategory) return
    
    const newSubType: SealSubType = {
      id: Date.now() + Math.random(),
      categoryId: selectedCategory.id,
      name: '',
      isActive: true
    }
    
    setCurrentSubTypes(prev => [...(prev || []), newSubType])
  }

  // 删除印章子类型
  const handleDeleteSubType = (subTypeId: number) => {
    setCurrentSubTypes(prev => (prev || []).filter(sub => sub.id !== subTypeId))
  }

  // 进入地区配置或价格配置
  const handleNextFromSubTypes = async () => {
    if (!selectedCategory) return
    
    // 过滤出有效的印章类型（名称不为空）
    const validSubTypes = currentSubTypes.filter(s => s.name.trim() !== '')
    
    if (validSubTypes.length === 0) {
      alert('请至少添加一个印章类型')
      return
    }
    
    // 保存印章类型
    const success = await saveClassify(selectedCategory.id, validSubTypes)
    if (!success) {
      alert('保存印章类型失败，请重试')
      return
    }
    
    setShowSubTypeModal(false)
    if (selectedCategory?.needsRegionBinding) {
      // 需要省市绑定，进入地区选择
      setShowRegionModal(true)
    } else {
      // 不需要省市绑定，直接进入价格配置
      setShowPriceModal(true)
      await loadGlobalPrices()
    }
  }


  // 选择城市
  const handleSelectCity = (province: Region, city: Region) => {
    const newCity = {
      provinceId: province.id,
      provinceName: province.name,
      cityId: city.id,
      cityName: city.name
    }
    
    setSelectedCities(prev => {
      const currentCities = prev || []
      const exists = currentCities.find(c => c.cityId === city.id)
      
      if (exists) {
        return currentCities.filter(c => c.cityId !== city.id)
      } else {
        return [...currentCities, newCity]
      }
    })
  }

  // 进入地区价格配置
  const handleConfigRegionPrices = async () => {
    setShowRegionModal(false)
    setShowPriceModal(true)
    // 直接设置空数组，不再调用loadRegionPrices接口
    setRegionPrices([])
  }

  // 加载地区价格配置 - 不再调用接口，默认为空
  const loadRegionPrices = async () => {
    // 不再调用getRegionPrice接口，默认设置为空数组
    setRegionPrices([])
  }

  // 加载全局价格配置
  const loadGlobalPrices = async () => {
    try {
      const token = localStorage.getItem('auth_token')
      const headers: Record<string, string> = {
        'Accept': 'application/json'
      }
      if (token) {
        headers['Authorization'] = token
      }

      const response = await fetch(`/huibanhao/seal/getGlobalPrice?typeId=${selectedCategory?.id}`, {
        method: 'GET',
        headers
      })
      const result = await response.json()
      if (result.code === 200 && Array.isArray(result.data)) {
        setGlobalPrices(result.data)
      } else {
        console.error('获取全局价格失败:', result.msg)
        setGlobalPrices([])
      }
    } catch (error) {
      console.error('获取全局价格失败:', error)
      setGlobalPrices([])
    }
  }

  // 递归渲染地区树
  const renderRegionTree = (regionList: Region[], level: number = 0) => {
    return regionList
      .filter(region => 
        region.name.toLowerCase().includes(searchTerm.toLowerCase())
      )
      .map(region => (
        <div key={region.id} className={`ml-${level * 4}`}>
          <div className="flex items-center justify-between p-2 hover:bg-gray-50 rounded-lg">
                  <div 
                    className="flex items-center space-x-2 flex-1 cursor-pointer"
                    onClick={() => region.children?.length > 0 && toggleRegionExpanded(region.id)}
                  >
                    {region.children?.length > 0 && (
                      <div className="p-0 h-6 w-6 flex items-center justify-center">
                        {expandedRegions.has(region.id) ? (
                          <ChevronDown className="h-4 w-4" />
                        ) : (
                          <ChevronRight className="h-4 w-4" />
                        )}
                      </div>
                    )}
                    <MapPin className="h-4 w-4 text-gray-400" />
                    <span className="font-medium">{region.name}</span>
                    <Badge variant="outline" className="text-xs">
                      {region.level === 1 ? '省' : region.level === 2 ? '市' : '区'}
                    </Badge>
                    <span className="text-sm text-gray-500">({region.code})</span>
                  </div>
          </div>
          {expandedRegions.has(region.id) && region.children?.length > 0 && (
            <div className="ml-4">
              {renderRegionTree(region.children, level + 1)}
            </div>
          )}
        </div>
      ))
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600">正在加载地区数据...</p>
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <div>
        <h1 className="text-2xl font-bold text-gray-900 dark:text-white">在线刻章配置</h1>
        <p className="text-gray-600 dark:text-gray-400 mt-1">
          管理在线刻章的印章材质、类型和价格配置
        </p>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card>
          <CardContent className="p-6">
            <div className="flex items-center">
              <div className="text-2xl font-bold text-blue-600">
                {regions.length}
              </div>
              <div className="ml-auto text-blue-600">
                <MapPin className="h-4 w-4" />
              </div>
            </div>
            <p className="text-xs text-muted-foreground">省份总数</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-6">
            <div className="flex items-center">
              <div className="text-2xl font-bold text-green-600">
                {regions.reduce((sum, province) => sum + (province.children?.length || 0), 0)}
              </div>
              <div className="ml-auto text-green-600">
                <MapPin className="h-4 w-4" />
              </div>
            </div>
            <p className="text-xs text-muted-foreground">城市总数</p>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-6">
            <div className="flex items-center">
              <div className="text-2xl font-bold text-purple-600">
                0
              </div>
              <div className="ml-auto text-purple-600">
                <Settings className="h-4 w-4" />
              </div>
            </div>
            <p className="text-xs text-muted-foreground">材质配置总数</p>
          </CardContent>
        </Card>
      </div>

      {/* 印章大类配置管理 */}
      <Card>
        <CardHeader>
          <CardTitle>印章分类配置管理</CardTitle>
          <CardDescription>
            选择印章大类并配置相应的材质、类型和价格
          </CardDescription>
        </CardHeader>
        <CardContent>
          {/* 印章大类展示 */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {(sealCategories || []).map((category) => (
              <Card key={category.id} className="border hover:shadow-md transition-shadow">
                <CardContent className="p-4">
                  <div className="flex items-center justify-between">
                    <div>
                      <h3 className="font-medium text-lg">{category.name}</h3>
                      <p className="text-sm text-gray-600 mt-1">{category.description}</p>
                      <div className="mt-2 flex items-center space-x-2">
                        <Badge variant="outline" className="text-xs">
                          {category.needsRegionBinding ? '需要省市配置' : '全国统一价格'}
                        </Badge>
                      </div>
          </div>
                    <Button 
                      variant="outline"
                      onClick={() => handleSelectCategory(category)}
                    >
                      配置
                    </Button>
            </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </CardContent>
      </Card>



      {/* 印章材质配置弹窗 */}
      {showMaterialModal && selectedCategory && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 w-full max-w-4xl max-h-[90vh] overflow-y-auto">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-xl font-bold">
                配置印章材质 - {selectedCategory.name}
              </h2>
              <Button 
                variant="ghost" 
                size="sm"
                onClick={() => setShowMaterialModal(false)}
              >
                <X className="h-4 w-4" />
              </Button>
            </div>

            <div className="space-y-4">
              <div className="flex justify-between items-center">
                <p className="text-gray-600">
                  管理该地区支持的印章材质类型
                </p>
                <Button onClick={handleAddMaterial}>
                  <Plus className="h-4 w-4 mr-2" />
                  添加材质
                </Button>
              </div>

              {/* 材质列表 */}
              <div className="border rounded-lg">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>材质名称</TableHead>
                      <TableHead>状态</TableHead>
                      <TableHead className="text-right">操作</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {(materials || []).map((material) => (
                      <TableRow key={material.id}>
                        <TableCell>
                          {material.id > 1000000000000 ? (
                            // 新添加的材质可以编辑名称
                            <Input
                              value={material.name}
                              onChange={(e) => handleUpdateMaterial(material.id, { name: e.target.value })}
                              placeholder="输入材质名称"
                            />
                          ) : (
                            // 已保存的材质只能显示，不能修改
                            <span className="font-medium">{material.name}</span>
                          )}
                    </TableCell>
                    <TableCell>
                          <Badge className={material.status === 0 ? "bg-green-100 text-green-800" : "bg-gray-100 text-gray-800"}>
                            {material.status === 0 ? '启用' : '禁用'}
                          </Badge>
                    </TableCell>
                    <TableCell className="text-right">
                      <div className="flex items-center justify-end space-x-2">
                            <Button 
                              variant="ghost" 
                              size="sm"
                              onClick={() => handleUpdateMaterial(material.id, { status: material.status === 0 ? 1 : 0 })}
                            >
                              {material.status === 0 ? '禁用' : '启用'}
                        </Button>
                            {material.id > 1000000000000 && (
                              // 只有新添加的材质才能删除
                              <Button 
                                variant="ghost" 
                                size="sm"
                                onClick={() => handleDeleteMaterial(material.id)}
                              >
                            <Trash2 className="h-4 w-4" />
                          </Button>
                            )}
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>

              {/* 操作按钮 */}
              <div className="flex justify-end space-x-2 pt-4">
                <Button 
                  variant="outline"
                  onClick={() => setShowMaterialModal(false)}
                >
                  取消
                </Button>
                <Button 
                  onClick={async () => {
                    if (!selectedCategory) return
                    
                    // 过滤出有效的材质（名称不为空）
                    const validMaterials = materials.filter(m => m.name.trim() !== '')
                    
                    if (validMaterials.length === 0) {
                      alert('请至少添加一个材质')
                      return
                    }
                    
                    const success = await saveMaterials(selectedCategory.id, validMaterials)
                    if (success) {
                      // 保存成功后，获取印章类型并进入配置
                      await handleConfigSubTypes()
                    } else {
                      alert('保存材质失败，请重试')
                    }
                  }}
                >
                  保存材质并配置印章类型
                </Button>
            </div>
            </div>
          </div>
        </div>
      )}

      {/* 印章子类型配置弹窗 */}
      {showSubTypeModal && selectedCategory && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 w-full max-w-4xl max-h-[90vh] overflow-y-auto">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-xl font-bold">
                配置印章类型 - {selectedCategory.name}
              </h2>
              <Button 
                variant="ghost" 
                size="sm"
                onClick={() => setShowSubTypeModal(false)}
              >
                <X className="h-4 w-4" />
              </Button>
            </div>

            <div className="space-y-4">
              <div className="flex justify-between items-center">
                <p className="text-gray-600">
                  管理该类别的印章子类型
                </p>
                <Button onClick={handleAddSubType}>
                  <Plus className="h-4 w-4 mr-2" />
                  添加子类型
              </Button>
            </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                {(currentSubTypes || []).map((subType) => (
                  <div key={subType.id} className="flex items-center space-x-2 p-3 border rounded-lg">
                    <input
                      type="checkbox"
                      checked={subType.isActive}
                      onChange={(e) => handleUpdateSubType(subType.id, { isActive: e.target.checked })}
                      className="w-4 h-4"
                    />
                    {subType.id > 1000000000000 ? (
                      // 新添加的类型可以编辑名称
                      <Input
                        value={subType.name}
                        onChange={(e) => handleUpdateSubType(subType.id, { name: e.target.value })}
                        placeholder="输入子类型名称"
                        className="flex-1 text-sm"
                      />
                    ) : (
                      // 已保存的类型只能显示，不能修改
                      <span className="flex-1 text-sm font-medium">{subType.name}</span>
                    )}
                    {subType.id > 1000000000000 && (
                      // 只有新添加的类型才能删除
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleDeleteSubType(subType.id)}
                        className="p-1 h-6 w-6 text-gray-400 hover:text-red-600"
                      >
                        <X className="h-3 w-3" />
                      </Button>
                    )}
          </div>
                ))}
              </div>

              <div className="flex justify-between pt-4">
                <Button 
                  variant="outline"
                  onClick={() => {
                    setShowSubTypeModal(false)
                    setShowMaterialModal(true)
                  }}
                >
                  上一步：配置材质
                </Button>
                <div className="space-x-2">
                  <Button 
                    variant="outline"
                    onClick={() => setShowSubTypeModal(false)}
                  >
                    取消
                  </Button>
                  <Button onClick={handleNextFromSubTypes}>
                    保存印章类型并{selectedCategory.needsRegionBinding ? '选择地区' : '配置价格'}
                  </Button>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 地区选择弹窗（仅公司和个体户） */}
      {showRegionModal && selectedCategory && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 w-full max-w-6xl max-h-[90vh] overflow-y-auto">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-xl font-bold">
                选择配置地区 - {selectedCategory.name}
              </h2>
              <Button 
                variant="ghost" 
                size="sm"
                onClick={() => setShowRegionModal(false)}
              >
                <X className="h-4 w-4" />
              </Button>
            </div>

            <div className="space-y-4">
              <div className="flex justify-between items-center">
                <p className="text-gray-600">
                  选择需要配置价格的省市（已选择 {(selectedCities || []).length} 个城市）
                </p>
              </div>


              {/* 已选择的城市 */}
              {(selectedCities || []).length > 0 && (
                <div className="border rounded-lg p-4 bg-gray-50">
                  <h4 className="font-medium mb-2">已选择的城市：</h4>
                  <div className="flex flex-wrap gap-2">
                    {(selectedCities || []).map((city) => (
                      <Badge key={city.cityId} className="bg-blue-100 text-blue-800">
                        {city.provinceName} - {city.cityName}
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => setSelectedCities(prev => prev.filter(c => c.cityId !== city.cityId))}
                          className="ml-1 p-0 h-4 w-4"
                        >
                          <X className="h-2 w-2" />
                        </Button>
                      </Badge>
                    ))}
                  </div>
                </div>
              )}

              {/* 搜索框 */}
              <div className="relative max-w-sm">
                <Search className="absolute left-3 top-3 h-4 w-4 text-gray-400" />
                <Input
                  placeholder="搜索省份或城市..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pl-10"
                />
              </div>

              {/* 省市列表 */}
              <div className="border rounded-lg p-4 max-h-96 overflow-y-auto">
                {regions.length > 0 ? (
                  regions
                    .filter(province => 
                      province.name.toLowerCase().includes(searchTerm.toLowerCase())
                    )
                    .map(province => (
                      <div key={province.id} className="mb-4">
                        <button
                          type="button"
                          className="w-full flex items-center space-x-2 p-2 hover:bg-gray-50 rounded-lg cursor-pointer text-left"
                          onClick={(e) => {
                            e.preventDefault()
                            e.stopPropagation()
                            toggleRegionExpanded(province.id)
                          }}
                        >
                          {province.children?.length > 0 && (
                            <div className="h-6 w-6 flex items-center justify-center">
                              {expandedRegions.has(province.id) ? (
                                <ChevronDown className="h-4 w-4" />
                              ) : (
                                <ChevronRight className="h-4 w-4" />
                              )}
                            </div>
                          )}
                          <MapPin className="h-4 w-4 text-gray-400" />
                          <span className="font-medium">{province.name}</span>
                        </button>
                        {expandedRegions.has(province.id) && (
                          <div className="ml-8 mt-2 grid grid-cols-2 md:grid-cols-3 gap-3">
                            {(province.children || [])
                              .filter(city => 
                                city.name.toLowerCase().includes(searchTerm.toLowerCase())
                              )
                              .map(city => {
                                const isSelected = (selectedCities || []).some(c => c.cityId === city.id)
                                return (
                                  <button
                                    key={city.id}
                                    type="button"
                                    className={`relative p-3 border-2 rounded-lg cursor-pointer transition-all duration-200 text-left font-medium ${
                                      isSelected 
                                        ? 'bg-gradient-to-r from-blue-50 to-blue-100 border-blue-500 text-blue-700 shadow-lg transform scale-105' 
                                        : 'border-gray-200 hover:border-blue-300 hover:bg-blue-50 hover:shadow-md'
                                    }`}
                                    onClick={(e) => {
                                      e.preventDefault()
                                      e.stopPropagation()
                                      handleSelectCity(province, city)
                                    }}
                                  >
                                    <span className="text-sm pointer-events-none">{city.name}</span>
                                    {isSelected && (
                                      <div className="absolute top-2 right-2 w-3 h-3 bg-blue-500 rounded-full flex items-center justify-center">
                                        <div className="w-1.5 h-1.5 bg-white rounded-full"></div>
                                      </div>
                                    )}
                                  </button>
                                )
                              })
                            }
                          </div>
                        )}
                      </div>
                    ))
                ) : (
                  <div className="text-center py-8 text-gray-500">
                    暂无地区数据
                  </div>
                )}
              </div>

              <div className="flex justify-between pt-4">
                <Button 
                  variant="outline"
                  onClick={() => {
                    setShowRegionModal(false)
                    setShowSubTypeModal(true)
                  }}
                >
                  上一步：配置类型
                </Button>
                <div className="space-x-2">
                  <Button 
                    variant="outline"
                    onClick={() => setShowRegionModal(false)}
                  >
                    取消
                  </Button>
                  <Button 
                    onClick={handleConfigRegionPrices}
                    disabled={(selectedCities || []).length === 0}
                  >
                    下一步：配置价格 ({(selectedCities || []).length})
                  </Button>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 印章价格配置弹窗 */}
      {showPriceModal && selectedCategory && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 w-full max-w-6xl max-h-[90vh] overflow-y-auto">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-xl font-bold">
                配置印章价格 - {selectedCategory.name}
              </h2>
              <Button 
                variant="ghost" 
                size="sm"
                onClick={() => setShowPriceModal(false)}
              >
                <X className="h-4 w-4" />
              </Button>
            </div>

            <div className="space-y-4">
              <p className="text-gray-600">
                {selectedCategory.needsRegionBinding 
                  ? `为每种材质和印章类型在不同城市配置价格（共 ${(selectedCities || []).length} 个城市）`
                  : '为每种材质和印章类型配置全国统一价格'
                }
              </p>
              
              {/* 价格配置说明 */}
              <div className="text-sm text-gray-500">
                请为启用的材质与印章类型填写价格信息。
              </div>

              {/* 价格配置表格 */}
              <div className="space-y-6">
                {(materials || []).length === 0 && (
                  <div className="text-center py-8 text-gray-500">
                    暂无材质数据，请先配置印章材质
                  </div>
                )}
                {(materials || []).filter(m => m.status === 0).length === 0 && (materials || []).length > 0 && (
                  <div className="text-center py-8 text-gray-500">
                    暂无启用的材质，请先启用印章材质
                  </div>
                )}
                {(materials || []).filter(m => m.status === 0).map((material) => (
                  <Card key={material.id} className="border">
                    <CardHeader className="pb-3">
                      <CardTitle className="text-lg">
                        {material.name} - 价格配置
                      </CardTitle>
                    </CardHeader>
                    <CardContent>
                      {selectedCategory.needsRegionBinding ? (
                        // 地区价格配置 - 统一配置所有选中城市的价格
                        <div className="space-y-4">
                          {/* 显示配置说明 */}
                          <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                            <h4 className="font-medium text-blue-800 mb-2">批量价格配置</h4>
                            <p className="text-sm text-blue-600 mb-2">
                              以下价格将应用到所有选中的城市：
                            </p>
                            <div className="flex flex-wrap gap-2">
                              {(selectedCities || []).map((city) => (
                                <span key={city.cityId} className="inline-flex items-center px-2 py-1 rounded-full text-xs bg-blue-100 text-blue-700">
                                  {city.provinceName} - {city.cityName}
                                </span>
                              ))}
                            </div>
                          </div>

                          {/* 统一价格配置表格 */}
                          <div className="border rounded-lg">
                            <Table>
                              <TableHeader>
                                <TableRow>
                                  <TableHead>印章类型</TableHead>
                                  <TableHead>原价(元)</TableHead>
                                  <TableHead>优惠价(元)</TableHead>
                                  <TableHead className="text-right">操作</TableHead>
                                </TableRow>
                              </TableHeader>
                              <TableBody>
                                {(currentSubTypes || []).filter(sub => sub.isActive).length === 0 ? (
                                  <TableRow>
                                    <TableCell colSpan={4} className="text-center py-4 text-gray-500">
                                      暂无启用的印章类型
                                    </TableCell>
                                  </TableRow>
                                ) : (
                                  (currentSubTypes || []).filter(sub => sub.isActive).map((subType) => {
                                    // 查找该材质和子类型的基础价格配置
                                    const basePrice = findRegionPrice(material.id, subType.id)
                                    
                                    return (
                                      <TableRow key={`${material.id}-${subType.id}`}>
                                        <TableCell>
                                          <div className="font-medium">{subType.name}</div>
                                        </TableCell>
                                        <TableCell>
                                          <Input
                                            type="number"
                                            value={basePrice?.price || ''}
                                            onChange={(e) => {
                                              const price = parseFloat(e.target.value) || 0
                                              updateRegionPrice(material.id, subType.id, 'price', price)
                                            }}
                                            placeholder="原价"
                                            className="w-24"
                                          />
                                        </TableCell>
                                        <TableCell>
                                          <Input
                                            type="number"
                                            value={basePrice?.discountPrice || ''}
                                            onChange={(e) => {
                                              const discountPrice = parseFloat(e.target.value) || 0
                                              updateRegionPrice(material.id, subType.id, 'discountPrice', discountPrice)
                                            }}
                                            placeholder="优惠价"
                                            className="w-24"
                                          />
                                        </TableCell>
                                        <TableCell className="text-right">
                                          {basePrice && (basePrice.price > 0 || basePrice.discountPrice > 0) && (
                                            <Button 
                                              variant="ghost" 
                                              size="sm"
                                              onClick={() => {
                                                // 批量删除所有相关的价格记录
                                                setRegionPrices(prices => 
                                                  prices.filter(p => 
                                                    !(p.materialId === material.id && p.subTypeId === subType.id)
                                                  )
                                                )
                                              }}
                                            >
                                              <Trash2 className="h-4 w-4" />
                                            </Button>
                                          )}
                                        </TableCell>
                                      </TableRow>
                                    )
                                  })
                                )}
                              </TableBody>
                            </Table>
                          </div>
                        </div>
                      ) : (
                        // 全局价格配置
                        <div className="border rounded-lg">
                          <Table>
                            <TableHeader>
                              <TableRow>
                                <TableHead>印章类型</TableHead>
                                <TableHead>原价(元)</TableHead>
                                <TableHead>优惠价(元)</TableHead>
                                <TableHead className="text-right">操作</TableHead>
                              </TableRow>
                            </TableHeader>
                            <TableBody>
                              {(currentSubTypes || []).filter(sub => sub.isActive).length === 0 ? (
                                <TableRow>
                                  <TableCell colSpan={4} className="text-center py-4 text-gray-500">
                                    暂无启用的印章类型
                                  </TableCell>
                                </TableRow>
                              ) : (
                                (currentSubTypes || []).filter(sub => sub.isActive).map((subType) => {
                                const existingPrice = findGlobalPrice(material.id, subType.id)
                                
                                return (
                                  <TableRow key={`${material.id}-${subType.id}`}>
                                    <TableCell>
                                      <div className="font-medium">{subType.name}</div>
                                    </TableCell>
                                    <TableCell>
                                      <Input
                                        type="number"
                                        value={existingPrice?.price || ''}
                                        onChange={(e) => {
                                          const price = parseFloat(e.target.value) || 0
                                          updateGlobalPrice(material.id, subType.id, 'price', price)
                                        }}
                                        placeholder="原价"
                                        className="w-24"
                                      />
                                    </TableCell>
                                    <TableCell>
                                      <Input
                                        type="number"
                                        value={existingPrice?.discountPrice || ''}
                                        onChange={(e) => {
                                          const discountPrice = parseFloat(e.target.value) || 0
                                          updateGlobalPrice(material.id, subType.id, 'discountPrice', discountPrice)
                                        }}
                                        placeholder="优惠价"
                                        className="w-24"
                                      />
                                    </TableCell>
                                    <TableCell className="text-right">
                                      {existingPrice && (existingPrice.price > 0 || existingPrice.discountPrice > 0) && (
                                        <Button 
                                          variant="ghost" 
                                          size="sm"
                                          onClick={() => setGlobalPrices(prices => prices.filter(p => p.id !== existingPrice.id))}
                                        >
                                          <Trash2 className="h-4 w-4" />
                                        </Button>
                                      )}
                                    </TableCell>
                                  </TableRow>
                                )
                              })
                              )}
                            </TableBody>
                          </Table>
                        </div>
                      )}
        </CardContent>
      </Card>
                ))}
              </div>

              {/* 操作按钮 */}
              <div className="flex justify-between pt-4">
                <Button 
                  variant="outline"
                  onClick={() => {
                    setShowPriceModal(false)
                    if (selectedCategory.needsRegionBinding) {
                      setShowRegionModal(true)
                    } else {
                      setShowSubTypeModal(true)
                    }
                  }}
                >
                  上一步：{selectedCategory.needsRegionBinding ? '选择地区' : '配置类型'}
                </Button>
                <div className="space-x-2">
                  <Button 
                    variant="outline"
                    onClick={() => setShowPriceModal(false)}
                  >
                    取消
                  </Button>
                  <Button onClick={async () => {
                    const token = localStorage.getItem('auth_token')
                    const headers: Record<string, string> = {
                      'Accept': 'application/json',
                      'Content-Type': 'application/json'
                    }
                    if (token) {
                      headers['Authorization'] = token
                    }

                    const payload: any = {
                      categoryId: selectedCategory?.id,
                      regionPrices
                    }

                    try {
                      const response = await fetch('/huibanhao/seal/saveRegionPrice', {
                        method: 'POST',
                        headers,
                        body: JSON.stringify(payload)
                      })
                      const result = await response.json()
                      if (result.code === 200) {
                        setShowPriceModal(false)
                        setSelectedCategory(null)
                        setSelectedCities([])
                        setCurrentSubTypes([])
                        setGlobalPrices([])
                        setRegionPrices([])
                      } else {
                        alert(result.msg || '保存配置失败')
                      }
                    } catch (error) {
                      console.error('保存配置失败:', error)
                      alert('保存配置失败')
                    }
                  }}>
                    保存配置
                  </Button>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
